﻿(function () {
  'use strict';
  angular
    .module('articles.admin')
		.controller('ArticlesAdminController', ArticlesAdminController)
		.filter('humanReadableFileSizeFilter', fileSizeFilter);

  fileSizeFilter.$inject = ['$filter'];
  ArticlesAdminController.$inject = ['$scope',
    '$state',
    '$window',
    'articleResolve',
    'Authentication',
    'Notification',
    'ArticlesService'
  ];

  function fileSizeFilter() {
    // See https://en.wikipedia.org/wiki/Binary_prefix
    var decimalByteUnits = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];

    return function (input) {
      var i = -1;
      var fileSizeInBytes = input;

      do {
        fileSizeInBytes = fileSizeInBytes / 1024;
        i++;
      } while (fileSizeInBytes > 1024);

      var result = decimalByteUnits[i];
      return Math.max(fileSizeInBytes, 0.1).toFixed(1) + ' ' + result;
    };
  }

  function ArticlesAdminController($scope, $state, $window, article, Authentication, Notification, ArticlesService) {
    var vm = this;

	  var newArt = new ArticlesService();
	  newArt.copyExistArt(article);

    vm.article = newArt;
    vm.authentication = Authentication;
    vm.form = {};
    vm.remove = remove;
    vm.save = save;
    vm.upload = addForUpload;
    vm.removeFromUploadList = removeFromUploadList;
    vm.removeImgsFromServer = removeImgsFromServer;
    vm.isAdminUser = isAdminUser;
    vm.isLoading = false;

    function isAdminUser() {
      return vm.authentication.user.roles.indexOf('admin') != -1;
    }

    // Remove existing Article
    function remove() {
      if ($window.confirm('Are you sure you want to delete?')) {
        vm.article.remove().then(function() {
          $state.go('admin.articles.list');
          Notification.success({ message: '<i class="glyphicon glyphicon-ok"></i> Article deleted successfully!' });
        });
      }
    }

    // Save Article
    function save(isValid) {
      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'vm.form.articleForm');
        return false;
      }

      vm.isLoading = true;

      // Create a new article, or update the current instance
      vm.article.createOrUpdate(vm.article)
        .then(successCallback, errorCallback);

      function successCallback(res) {
        if(vm.authentication.user.roles.indexOf('admin') != -1) {
          $state.go('admin.articles.list'); // should we send the User to the list or the updated Article's view?
        }
        else {
          $state.go('home');
        }

        vm.isLoading  = false;
        Notification.success({ message: '<i class="glyphicon glyphicon-ok"></i> Article saved successfully!' });
      }

      function errorCallback(res) {
        vm.isLoading  = false;
        Notification.error({ message: res.data.message, title: '<i class="glyphicon glyphicon-remove"></i> Article save error!' });
      }
    }

    function addForUpload($files) {
      vm.article.uploadFileList = vm.article.uploadFileList.concat($files);
    }

    function removeFromUploadList(index) {
      vm.article.uploadFileList.splice(index, 1);
    }

    function removeImgsFromServer(index) {
      vm.article.removeImgsFromServer(index);
    }

  }
}());
